<template>
  <view class="goods-detail">
    <view >
      <view class="container" v-if="info.goods_id">
        <view class="swiper">
          <swiper
              :autoplay="autoplay"
              @change="setCurrent"
              class="banner-box swiper-box"
              :duration="duration"
              :indicator-dots="indicatorDots"
              :interval="interval"
              :circular="true"
          >
            <swiper-item @tap="previewImages" :data-index="index" v-for="(item, index) in info.images" :key="index">
              <image class="slide-image" mode="aspectFill" :src="item"></image>
            </swiper-item>
          </swiper>
          <view class="number-banner">
            <text>{{ currentIndex }}</text>
            <text>/{{ info.images.length }}</text>
          </view>
        </view>
        <view class="cont-box b-f">
          <view class="dis-flex flex-y-center">
            <view class="left flex-box dis-flex flex-dir-column">
              <view class="goods-title">
                <text class="title f-32 twolist-hidden">{{ info.goods_name }}</text>
              </view>
              <view class="money-box">
                <text class="col-m f-26">￥</text>
                <text class="price col-m">{{ goods_price }}</text>
                <text class="del" v-if="market_price > 0">￥{{ market_price }}</text>
              </view>
            </view>
            <view class="right goods__share" v-if="enable_share">
              <form @submit="openActionsheet" :report-submit="true">
                <button formType="submit" class="share-btn dis-flex flex-dir-column">
                  <text class="share__icon iconfont icon-fenxiang"></text>
                  <text class="f-24">分享</text>
                </button>
              </form>
            </view>
          </view>
          <view class="goods-sales-box f-28 dis-flex">
            <text class="flex-box num">销量：{{ info.sales_num }}</text>
            <text class="flex-box stock">库存：{{ store_count }}</text>
          </view>
        </view>
        <view @tap="onChangeShowState" class="cont-box b-f goods-property-box m-top20">
          <text class="col-3 f-30">已选</text>
          <text class="col-3 f-30 pl-12">{{ goods_num }} 个</text>
          <view class="goods-property-jianTou">
            <text
                :class="'iconfont icon-xiangyoujiantou user-orderJtou-1 ' + (showView ? 'user-orderJtou-2' : '')"></text>
          </view>
        </view>
        <view :class="'cart v-hide ' + (showView ? 'v-show' : '')">
          <view class="modal_cont_box">
            <scroll-view class="goods-list-box" :scroll-y="true">
              <view class="spce_list" v-if="info.spec_list.length">
                <view class="cf tmall-types">
                  <view class="tipstxt">商品规格</view>

                  <view class="cf cartypelist" v-for="(item, item_idx) in info.spec_list" :key="item_idx">
                    <view @tap="clickSpec(item.spec_id)"
                          :class="'cartypeitem '+( current_spec_id===item.spec_id?'cur':'')">
                      {{ item.spec_name }}
                    </view>
                  </view>
                </view>
              </view>

              <view class="buy_number">
                <view class="buyNumber f-26">
                  <text>购买数量</text>
                </view>
                <view class="selectNumber">
                  <button @tap="down" :class="'default  ' + (goods_num > 1 ? '' : ' default-active')" type="default">-
                  </button>
                  <input @input="importFun" type="number" :value="goods_num" disabled/>
                  <button @tap="up" class="default" type="default">+</button>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>

        <!-- 商品评价 -->
        <view class="goods_comment" v-if="info.comment_list && info.comment_list.length">
          <view class="cont-box b-f goods-property-box m-top20">
            <text class="col-3 f-30">评价 ({{ info.comment_count }}条)</text>
            <text @tap="navigateToComment" class="comment-num">查看更多</text>
            <view class="goods-property-jianTou">
              <text class="iconfont icon-xiangyoujiantou user-orderJtou" style="margin-top: 0"></text>
            </view>
          </view>
          <view class="goods_comment_box b-f" v-for="(item, index) in info.comment_list" :key="index">
            <view class="cont-box goods-comment-box b-t b-f b-b">
              <view class="dis-flex">
                <view class="user">
                  <text class="user_name f-26">{{ item.username }}</text>
                </view>
                <view class="com_xing">
                  <text
                      v-for="n in 5"
                      :key="n"
                      class="iconfont icon-shoucang"
                      :class="{ active: n <= item.score }"
                  ></text>

                </view>
              </view>
              <view class="goods-comment-cont m-top20">
                <text class="f-26 twolist-hidden">{{ item.content }}</text>
              </view>
              <view class="f-22 col-9 m-top10">{{ item.created_at }}</view>
            </view>
          </view>
        </view>

        <!-- 商品描述 -->
        <view class="p-bottom">
          <view class="top-nav m-top20 b-f b-b">
            <view class="top-nav-bar">
              <view @tap="toOrder" id="top-nav-bar-true">
                <span>商品详情</span>
              </view>
            </view>
          </view>
          <view class="detail-content" v-if="!hiddenOrder">
            <view v-if="info.goods_content !== ''">
              <view class="b-f goods-detail-box">
                <view class="goods-cont-li">
                  <u-parse :html="info.goods_content" :selectable="true"></u-parse>
                </view>
              </view>
            </view>
            <view v-else>
              <view class="bsshop-notcont">
                <text class="iconfont icon-wushuju"></text>
                <text class="cont">亲,此处暂无详情数据</text>
              </view>
            </view>
          </view>
          <view class="services" v-if="info.service">
            <view class="title">
              <text>服务保障</text>
            </view>
            <view class="services-list">
              <view class="service-item" v-for="(s,id) in info.service" :key="id">
                <view class="service-title">{{ s.name }}</view>
                <view class="service-cont">
                  <text>{{ s.desc }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 底部操作栏 -->
        <view class="footer-fixed f-30">
          <view class="goods-fixed-icon" @click="goService">
            <image class="flow-img" src="/static/images/kefu.png"></image>
            <view class="flow_num" v-if="kefu_num">
              <text>{{ kefu_num > 99 ? '99+' : kefu_num }}</text>
            </view>
          </view>
          <view @tap="toCart" class="goods-fixed-icon">
            <image class="flow-img" src="/static/tab-bar/cart.png"></image>
            <view class="flow_num" v-if="cart_total_num > 0">
              <text>{{ cart_total_num > 99 ? '99+' : cart_total_num }}</text>
            </view>
          </view>
          <template v-if="store_count > 0">
            <view @tap="submit" class="order-number" data-type="addCart">加入购物车</view>
            <view @tap="submit" class="order-bt" data-type="buyNow">立即购买</view>
          </template>
          <view class="default-btn" style="width: 100%" v-else>该属性暂无现货</view>
        </view>
      </view>
    </view>

    <!-- 返回顶部 -->
    <view @tap="goTop" @click="goTop" class="widget-goTop" v-if="floorstatus">
      <text class="iconfont icon-fanhuidingbu"></text>
    </view>

    <!-- 分享按钮 -->
    <action-sheet
        :show="share.show"
        :actions="share.actions"
        :cancel-text="share.cancelText"
        :cancel-with-mask="share.cancelWithMask"
        @cancel="closeActionSheet"
        @actionclick="clickAction"
        mask-class="tiny"
    />

    <!-- 商品海报 弹出层 -->
    <c_popup :show="share.showPopup" @close="togglePopup">
      <view class="pop-poster pop-example__container">
        <!-- 关闭按钮 -->
        <view class="pop-close dis-flex flex-x-center flex-y-center" @tap="togglePopup">
          <text class="iconfont icon-shanchu f-30 col-9"></text>
        </view>
        <form @submit="savePoster" :report-submit="true">
          <view class="poster__image">
            <image mode="widthFix" :src="qrcode"></image>
          </view>
          <view class="poster__tips m-top10 t-c">
            <text class="f-24 col-9">保存图片后，可分享到朋友圈</text>
          </view>
          <view class="padding-box m-top10 profile-btn">
            <button formType="submit">保存图片</button>
          </view>
        </form>
      </view>
    </c_popup>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
  </view>
</template>

<script>
import ActionSheet from "@/components/actionsheet/c_actionsheet.vue";
import c_popup from "@/components/popup/c_popup.vue";
import goods_api from "@/common/goods_api";
import cart_api from "@/common/cart_api";

export default {
  components: {
    ActionSheet,
    c_popup
  },
  data() {
    return {
      enable_share: false,
      info: {},
      spec_obj: {},
      current_spec_id: 0,//当前规格id
      indicatorDots: true, // 是否显示面板指示点
      autoplay: true,   // 是否自动切换
      interval: 3000, // 自动切换时间间隔
      duration: 800, // 滑动动画时长
      currentIndex: 1,  // 轮播图指针
      floorstatus: false,// 返回顶部
      showView: true,//是否显示规格

      goods_price: 0,
      market_price: 0,
      store_count: 0,
      goods_num: 1,
      cart_total_num: 0,

      // 分享按钮组件
      share: {
        show: false,
        cancelWithMask: true,
        cancelText: '关闭',
        actions: [
          {
            name: '生成商品海报',
            className: 'action-class',
            loading: false
          },
          {
            name: '发送给朋友',
            openType: 'share'
          }
        ],
        // 商品海报
        showPopup: false
      },
      scrollTop: 0,
      hiddenOrder: '',
      qrcode: '',
      kefu_num: 0,
      kefu_info: null
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    let that = this;
    //let scene = app.globalData.getSceneData(e); // 商品id
    that.item_id = e.item_id ? e.item_id : scene.gid;
    // 获取商品信息
    that.getGoodsDetail();
  },
  onPageScroll(e) {
      this.scrollTop = e.scrollTop;
  },
  /**
   * 分享当前页面
   */
  onShareAppMessage: function () {
    // 构建页面参数
    let params = app.globalData.urlEncode({
      item_id: this.item_id,
      referee_id: app.globalData.getUserId()
    });
    return {
      title: this.info.goods_name,
      desc: '',
      path: '/pages/goods/detail?' + params
    };
  },

  methods: {
    /**
     * 获取商品信息
     */
    getGoodsDetail: function () {
      let that = this;
      goods_api.detail({
        item_id: that.item_id
      }).then(res => {
        if (res.code !== 0) {
          that.show_msg(res.msg, 'error', 2000, () => {
            uni.navigateBack()
          })
          return;
        }
        that.setData(res.data);
        that.initGoodsDetailData(res.data);
      })
    },

    /**
     * 初始化商品详情数据
     */
    initGoodsDetailData: function (data) {
      let that = this;
      if (data.info.spec_list.length > 0) {
        //数组转对象
        for (const item of data.info.spec_list) {
          that.spec_obj[item.spec_id] = item;
        }
        const spec = data.info.spec_list[0];
        that.clickSpec(spec.spec_id)

      } else {
        //非多规格
        that.setData({
          goods_price: data.info.goods_price,
          market_price: data.info.market_price,
          store_count: data.info.store_count
        })
      }
      return data;
    },


    clickSpec(spec_id) {
      this.current_spec_id = spec_id;

      let spec = this.spec_obj[spec_id]
      this.setData({
        goods_price: spec.price,
        store_count: spec.store_count,
        market_price: spec.market_price
      })
    },

    /**
     * 设置轮播图当前指针 数字
     */
    setCurrent(e) {
      this.setData({
        currentIndex: e.detail.current + 1
      });
    },

    /**
     * 控制商品规格/数量的显示隐藏
     */
    onChangeShowState() {
      this.setData({
        showView: !this.showView
      });
    },

    /**
     * 返回顶部
     */
    goTop(t) {
     uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      });
    },



    /**
     * 增加商品数量
     */
    up() {
      this.setData({
        goods_num: ++this.goods_num
      });
    },

    /**
     * 减少商品数量
     */
    down() {
      if (this.goods_num > 1) {
        this.setData({
          goods_num: --this.goods_num
        });
      }
    },

    /**
     * 跳转购物车页面
     */
    toCart() {
      uni.switchTab({
        url: '/pages/cart/index'
      });
    },

    goService() {
      if (!this.hasLogin) {
        return this.gotoPath('/pages/login/index?from=goods_detail' + this.serializeParam(this.options), false)
      }
      return this.gotoPath('/pages/packageA/kefu/chat?goods_id=' + this.item_id + '&' + this.kefu_info, false)
    },

    /**
     * 加入购物车and立即购买
     */
    submit(e) {
      if (!this.hasLogin) {
        return this.gotoPath('/pages/login/index?from=goods_detail' + this.serializeParam(this.options), false)
      }
      let that = this;
      let submitType = e.currentTarget.dataset.type;
      if (submitType === 'buyNow') {
        // 立即购买
        cart_api.action({
          order_type: 'buyNow',
          item_id: that.item_id,
          goods_num: that.goods_num,
          spec_id: that.current_spec_id,
        }).then(res => {
          this.$u.toast(res.msg)
          if (res.code !== 0) {
            return;
          }
          let options = this.serializeParam({
            order_type: 'buyNow',
            item_id: that.item_id,
            goods_num: that.goods_num,
            spec_id: that.current_spec_id,
          })
          uni.navigateTo({
            url: '/pages/cart/checkout?' + options
          })
        })

      } else if (submitType === 'addCart') {
        cart_api.action({
          order_type: 'addCart',
          item_id: that.item_id,
          goods_num: that.goods_num,
          spec_id: that.current_spec_id,
        }).then(res => {
          this.$u.toast(res.msg)
          that.setData(res.data);
        })

      }
    },

    /**
     * 浏览商品图片
     */
    previewImages(e) {
      let index = e.currentTarget.dataset.index;
      let imageUrls = this.info.images;
      uni.previewImage({
        current: imageUrls[index],
        urls: imageUrls
      });
    },

    /**
     * 跳转到评论
     */
    navigateToComment() {
      uni.navigateTo({
        url: '/pages/packageA/comment/index?item_id=' + this.item_id
      });
    },

    /**
     * 显示分享选项
     */
    openActionsheet(e) {
      this.setData({
        'share.show': true
      });
    },

    /**
     * 关闭分享选项
     */
    closeActionSheet() {
      this.setData({
        'share.show': false
      });
    },

    /**
     * 点击分享选项
     */
    clickAction(e) {
      if (e.detail.index === 0) {
        // 显示商品海报
        this.showPoster();
      }
      this.closeActionSheet();
    },

    /**
     * 切换商品海报
     */
    togglePopup() {
      this.setData({
        'share.showPopup': !this.share.showPopup
      });
    },

    /**
     * 显示商品海报图
     */
    showPoster() {
      let that = this;
      uni.showLoading({
        title: '加载中'
      });
      app.globalData._get(
          'item/poster',
          {
            item_id: that.item_id
          },
          function (result) {
            that.setData(result.data, function () {
              that.togglePopup();
            });
          },
          null,
          function () {
            uni.hideLoading();
          }
      );
    },

    /**
     * 保存海报图片
     */
    savePoster(e) {
      let that = this;
      uni.showLoading({
        title: '加载中'
      });
      // 下载海报图片
      uni.downloadFile({
        url: that.qrcode,
        success: function (res) {
          uni.hideLoading();
          // 图片保存到本地
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              uni.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              });
              // 关闭商品海报
              that.togglePopup();
            },
            fail: function (err) {
              if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
                uni.showToast({
                  title: '请允许访问相册后重试',
                  icon: 'none',
                  duration: 1000
                });
                setTimeout(function () {
                  uni.openSetting();
                }, 1000);
              }
            },
            complete(res) {
              console.log('complete');
              // wx.hideLoading();
            }
          });
        }
      });
    },

    importFun() {
      console.log('占位：函数 import 未声明');
    },

    toOrder() {
      console.log('占位：函数 toOrder 未声明');
    }
  }
};
</script>
<style lang="scss">
@import 'detail.scss';
</style>
